<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- 搜索 -->
    <!-- 旧件入库 -->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="120" @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'records'"
      :fetchapi="fetchApi"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :isSelectColumn="false"
    >
    <template slot="controls" slot-scope="props">
<!--        <span :style="{padding: '10px 10px'}" v-if="appId == 'beijing'"><multiuse-button size="small" type="primary"  @click="buoHui()" >批量驳回</multiuse-button></span>-->
<!--        <multiuse-button size="small" type="primary"  @click="buoHui()" >批量驳回</multiuse-button>-->
<!--        <multiuse-button size="small" type="primary" :click="tongGuo.bind()">批量通过</multiuse-button>-->
<!--        <multiuse-button size="small" type="primary" :click="BuHeGe.bind()">批量不合格</multiuse-button>-->
        <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
     </template>
    </FilterTable>
    <Drawer :visible.sync="visible" :title="'旧件入库详情'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DetailForm @close="close" @save="save" :rowData="returnId"></DetailForm>
    </Drawer>
    <Drawer :visible.sync="visible2" :title="'旧件入库编辑'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditForm @close="close2" @save="editSave" :rowData="returnId"></EditForm>
    </Drawer>
    <BaseDialog :visible.sync="selectDelearFlag" :title="'服务中心选择'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple"/>
    </BaseDialog>
          <BaseDialog
      :visible.sync="boHuiAdd"
      :title="'驳回原因'"
      width="850px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >

      <ReturnForm @close="closeboHui" @save="saveboHui" :boHuiIds="boHuiIds"> </ReturnForm>
    </BaseDialog>
    <BasePrint ref="templateEncasement" :data="waitEncasementList" template="waitReturnLabel/encasement" />

  </div>
  </Spin>
</template>
<script>
import moment from "moment";
import DetailForm from './DetailForm.vue';
import ReturnForm from './ReturnForm.vue';
import EditForm from './EditForm.vue';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { exportExcelFile } from '@/utils/index';
import { getPartType } from '@/api/dictionary/index.js';
import {
  getListByPage,
  getListForExport,
  piLiangTongGuo,
  piLiangBuoHui,
  piLiangBuHeGe,
  exporturl,
  generateLabel,
  getListForExportNew, generateReturnBoxList
} from '@/api/usedPartsReturnManage/usedPartsReturn_OEM/usedPartsWarehousing';
import { getAppId } from '@/assets/js/auth';
import {getPreReturnListForExportNew} from "@/api/usedPartsReturnManage/usedPartsReturn_DLR/usedPartsWaitReturnQuery";

export default {

  components: {
    DetailForm,
    EditForm,
    ReturnForm,
    DealerList
  },
  data() {
    return {
      waitEncasementList:{
        rows:[{

        }]
      },
      ownerCode: null,
      loading: false,
      dataList: [],
      boHuiIds: [],
      boHuiAdd: false,
      visible: false,
      visible2: false,
      selectDelearFlag: false,
      visibleDrawer: false,
      collapse: true,
      returnId: null,
      infoId: null,
      fetchApi: getListByPage,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      appId: null,
      fetchParams: {
        returnStatusStrs : '55881003,55881005,55881007,55881008',
        xhrAbort: true,
        ownerCode: null
      }, //ipa 接口
      selectedRows: [], //选中服务站
      dialogTitle: '选择车辆',
      visibleAdd: false,
      dealerList: [],
      dealerCompanyCode: [],
      dealerData: [],
      selectDealerData: []
    };
  },
  async created() {
    this.chuqi();
    this.appId = await getAppId();
    this.fetchParams.beginDlDate = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    this.fetchParams.endDlDate = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
  },
  methods: {
    //旧件状态下拉框
    async chuqi() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 5588 });

      console.log("==========",res.data);
      if (res.resultCode == 200) {
        res.data = res.data.filter(x => (x.codeId == 55881003 || x.codeId == 55881005 || x.codeId == 55881007 || x.codeId == 55881008));
        this.topFilterInit.find(x => x.fieldName == 'returnStatus').initialValue = '';
        this.topFilterInit.find(x => x.fieldName == 'returnStatus').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    // 导出
   async exportFileBtn() {
     try {
       // let params = { reportNo: "RE202103060001" }
       let params = {...this.fetchParams}
       let res = await getListForExportNew(params);
       exportExcelFile(res.data, '旧件入库列表')
     } catch (err) {
       console.warn(err)
     }
     // getListForExport(this.fetchParams)
      // let json = Object.assign({}, { CODE: 'CODE_00000175' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      // let beginSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginDlDate|endDlDate").initialValue[0];
      // let endSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginDlDate|endDlDate").initialValue[1];
      // if(!beginSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '入库开始日期不可为空！' });
      //   return
      // }
      // if(!endSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '入库结束日期不可为空！' });
      //   return
      // }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '入库日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '入库日期跨度不可超过十二个月！' });
      //     return
      //   }
      // }
      // let obj = Object.assign({}, this.fetchParams, {xhrAbort: false});
      // obj.beginDlDate = this.topFilterInit.find(x => x.fieldName == "beginDlDate|endDlDate").initialValue[0];
      // obj.endDlDate = this.topFilterInit.find(x => x.fieldName == "beginDlDate|endDlDate").initialValue[1];
      // console.log("=== 点击导出 ===")
      // getListForExport(obj).then(res => {
      //   exportExcelFile(res.data, '旧件入库');
      // });
    },
    //打印装箱检验单
    async examineInList(val) {
      var res = await generateReturnBoxList({returnId: val.returnId})
      if (res.resultCode === 200) {
        this.waitEncasementList.rows = res.data.dtlList;
        this.$nextTick(() => {
          this.$refs.templateEncasement.EXCUTE_PRINT();
        });
      }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.TurnOn =
      console.log(this.selectedRows);
    },
    close() {
      this.visible = false;
    },
    close2() {
      this.visible2 = false;
    },
    chooseOrderNo(val) {
      this.returnId = val;
      console.log("明细ID",val)
      this.visible = true;
    },
    chooseOrderNo2(val) {
      this.returnId = val;
      console.log("编辑ID",val)
      this.visible2 = true;
    },
    save(obj) {
      this.topFilterInit.find(x => x.fieldName == 'model').initialValue = obj[0].address;
      this.visible = false;
    },
    editSave(obj) {
      // this.topFilterInit.find(x => x.fieldName == 'model').initialValue = obj[0].address;
      this.visible2 = false;
      this.fetchParams = { ...this.fetchParams };
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    //服务站选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    },
    //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //保存
    Delearsave(val) {
      console.log(val)
      this.dealerData = val;
      this.selectDealerData = [];
      // this.dealer = {...val[0]};
      // this.ownerCode = val[0].dealerCompanyCode;
      let ownerCodeArr = [];
      let dealerNameArr = [];
      val.forEach(item => {
        ownerCodeArr.push(item.dealerCompanyCode);
        this.selectDealerData.push(item.dealerCompanyCode);
        // ownerCodeArr.push(item.dealerCode);
        dealerNameArr.push(item.dealerName);
      });
      // this.topFilterInit.find(x => x.fieldName == 'showOwnerCode').initialValue = dealerNameArr.join(",");
      if (ownerCodeArr.length > 0) {
        this.fetchParams.ownerCode = ownerCodeArr.join(",");
        console.log("ownerCode", this.fetchParams.ownerCode)
      }
      this.selectDelearFlag = false;
    },
    //搜索获取数据
    changeHandle(val) {
      if(!val.beginDlDate) {
        this.$notify.warning({ title: '提示信息', message: '入库开始日期不可为空！' });
        return
      }
      if(!val.endDlDate) {
        this.$notify.warning({ title: '提示信息', message: '入库结束日期不可为空！' });
        return
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(val.endDlDate).format('YYYY-MM-DD')).diff(moment(val.beginDlDate), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '入库日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(val.endDlDate).format('YYYY-MM-DD')).diff(moment(val.beginDlDate), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '入库日期跨度不可超过十二个月！' });
          return
        }
      }
      if (!this.ownerCode) {
        this.ownerCode = val.showOwnerCode
      }
      if (!val.showOwnerCode) {
        this.ownerCode = null
      }
      this.fetchParams = Object.assign({ownerCode: this.ownerCode}, this.fetchParams, val,{xhrAbort: false});
      console.log(val);
    },
    resetHandle(val){
      console.log("reset")
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams.ownerCode = null;
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
    },
    //批量通过
    async tongGuo() {
      if (this.selectedRows.length > 0) {
        this.loading = true;
        let turnOn = true;
        let turnOn2 = true;
        this.selectedRows.map(x => {
          if (x.returnStatus !== 55881002) {
            return turnOn = false;
          }
          if (x.statusStr !== '已回运') {
            return turnOn2 = false;
          }
        });
        //通知单状态已装箱  通知单状态为已回运
        if (turnOn === true && turnOn2 === true) {

          let arr = [];
          this.selectedRows.map(x => {
            arr.push(x.returnId);
          });

          const res = await piLiangTongGuo({returnIds: arr});
          this.fetchParams = {...this.fetchParams};
          this.loading = false;
        } else {
          this.loading = false;
          return this.$notify.warning({title: '提示信息', message: '批量入库不能包含已入库或已装箱状态'});
        }
      } else {
        return this.$notify.warning({title: '提示信息', message: '请选择单据！'});
      }

    },

    //批量不合格
    async BuHeGe() {
      console.log("7788");
      if (this.selectedRows.length > 0) {
        //this.loading = true;
          let arr = [];
          this.selectedRows.map(x => {
            arr.push(x.returnId);
          });
        console.log("wwwww");
        const res = await piLiangBuHeGe({returnIds: arr});
        if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '操作成功！！' });
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
          //this.loading = false;
          console.log("mmmmmm");
      } else {
        return this.$notify.warning({title: '提示信息', message: '请选择单据！'});
      }

    },
     saveboHui(val) {
      this.rowData = val;
      this.boHuiAdd = false;
       this.fetchParams = { ...this.fetchParams };

    },
        closeboHui() {
      this.boHuiAdd = false;
    },
    //批量驳回
     buoHui(val) {
      this.boHuiIds = [];
      this.boHuiIds.push({ returnId: val});
      this.boHuiAdd = true;
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'SELECT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
          onChange: val => {
            console.log(val)
          }
        },
        { type: 'SELECT', label: '回运单状态', fieldName: 'returnStatus', placeholder: '请选择通知单状态...', initialValue: '', itemList: [] },
        { type: 'INPUT', label: '回运单号', fieldName: 'returnNo', placeholder: '请输入通知单号...', initialValue: '' },
        {
          type: 'RANGE_DATE',
          label: '回运发运时间',
          fieldName: 'beginDlDate|endDlDate',
          placeholder: '请输入',
          initialValue: [
            moment()
              .startOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
            moment()
              .endOf('week')
              .format('YYYY-MM-DD HH:mm:ss')
          ],
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        { type: 'INPUT', label: '旧件代码', fieldName: 'partCode', placeholder: '请输入旧件代码...', initialValue: '' },
        { type: 'INPUT', label: '旧件名称', fieldName: 'partName', placeholder: '请输入旧件名称...', initialValue: '' }
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 250,
          render: (props, h) => {
            if (props.row.statusStr === '已签收') {
              return (
                <div style="text-align:center">
                  <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo(props.row)}>
                    明细
                  </multiuse-button>
                  <el-divider direction="vertical"/>
                  <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo2(props.row)}>
                    入库
                  </multiuse-button>
                  <el-divider direction="vertical"/>
                  <multiuse-button size="mini" type="text" onClick={() => this.examineInList(props.row)}>
                    打印装箱检验单
                  </multiuse-button>
                </div>
              );
            }else if (props.row.statusStr === '暂存入库') {
              return (
                <div style="text-align:center">
                  <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo(props.row)}>
                    明细
                  </multiuse-button>
                  <el-divider direction="vertical"/>
                  <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo2(props.row)}>
                    入库
                  </multiuse-button>
                  <el-divider direction="vertical"/>
                  <multiuse-button size="mini" type="text" onClick={() => this.examineInList(props.row)}>
                    打印装箱检验单
                  </multiuse-button>
                </div>
              );
            } else if (props.row.statusStr === '已部分入库') {
              return (
                <div style="text-align:center">
                  <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo(props.row)}>
                    明细
                  </multiuse-button>
                  <el-divider direction="vertical"/>
                  <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo2(props.row)}>
                    入库
                  </multiuse-button>
                </div>
              );
            } else if (props.row.statusStr === '已入库') {
              return (
                <div style="text-align:center">
                  <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo(props.row)}>
                    明细
                  </multiuse-button>
                  <el-divider direction="vertical"/>
                  <multiuse-button size="mini" type="text" onClick={() => this.examineInList(props.row)}>
                    打印入库单
                  </multiuse-button>
                </div>
              );
            } else {
              return (
                <div style="text-align:center">
                  <multiuse-button size="mini" type="text" onClick={() => this.chooseOrderNo(props.row)}>
                    明细
                  </multiuse-button>
                </div>
              );
            }
          }
        },
        { title: '通知单状态', dataIndex: 'statusStr', sorter: true, width: 100 },
        { title: '服务中心代码', dataIndex: 'ownerCode', sorter: true, width: 100},
        { title: '服务中心名称', dataIndex: 'dealerName', sorter: true, width: 220 },
        { title: '通知单号', dataIndex: 'returnNo', sorter: true },
        { title: '索赔单数', dataIndex: 'claimNum', sorter: true },
        { title: '旧件数量', dataIndex: 'partNum', sorter: true },
        // { title: '旧件索赔总金额', dataIndex: 'partAmount', sorter: true },
        { title: '通知时间', dataIndex: 'dlDate', sorter: true ,dateFormat: 'YYYY-MM-DD'},
        // { title: '运输方式', dataIndex: 'expressTypeStr', sorter: true },
        // { title: '驳回原因', dataIndex: 'returnMsg', sorter: true }
      ];
    }
  }
  // mounted() {
  //   this.BaseTable = this.$refs.listModal.$refs.pageTable;
  // }
};
</script>

<style lang="less" scoped></style>
